package connection;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.List;

/**
 * MongoDB连接工具类
 * @author lihaoshan
 * @date 2018-05-30
 * */
public class MongoConnection {

    /**
     * 需要验证用户名、密码的连接方式
     * @return mongoDatabase
     * */
    public MongoDatabase getConnection(){
        try{
            //连接到MongoDB服务，如果是远程连接可以将localhost改为服务器所在的IP地址
            //ServerAddress（）参数分别为服务器地址、端口
            ServerAddress serverAddress = new ServerAddress("localhost",27017);
            List<ServerAddress> serverAddressList = new ArrayList<ServerAddress>();
            serverAddressList.add(serverAddress);

            //createScramSha1Credential（）参数分别为用户名、数据库名称、密码
            MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("userName","databaseName","password".toCharArray());
            List<MongoCredential> mongoCredentialList = new ArrayList<MongoCredential>();
            mongoCredentialList.add(mongoCredential);

            //通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(serverAddressList,mongoCredentialList);

            //连接数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
            System.out.println("MongoDB连接成功");
            return mongoDatabase;
        } catch (Exception e){
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        return null;
    }

    /**
     * 不需要验证用户名、密码的连接方式
     * @return mongoDatabase
     * */
    public MongoDatabase getConnectionBasis(){
        try{
            //连接到MongoDB服务
            MongoClient mongoClient = new MongoClient("localhost",27017);
            MongoDatabase mongoDatabase = mongoClient.getDatabase("users");
            System.out.println("MongoDB连接成功");
            return mongoDatabase;
        } catch (Exception e){
            System.out.println(e.getClass().getName() + "：" + e.getMessage());
        }
        return null;
    }

}
